<?php
/**
 * 角色管理
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2017/2/26
 * Time: 11:33
 */

namespace app\admin\controller;

use app\common\controller\AdminBase;
use app\common\model\Access as AccessModel;
use app\common\model\BoolStatus;
use app\common\model\Role as RoleModel;
use app\admin\validate\Role as RoleValidate;
use app\common\model\RoleAccess as RoleAccess;
use think\Db;

class Role extends AdminBase
{
    /**
     * 角色列表
     * @return mixed
     */
    public function index()
    {
        $roleModel = new RoleModel();
        $list      = $roleModel->paginate($this->pageSize);

        // 获取分页显示
        $page = $list->render();
        // 模板变量赋值
        $this->assign('list', $list);
        $this->assign('page', $page);

        $status = BoolStatus::getLables();
        $this->assign('status', $status);
        return $this->fetch('role/index');
    }


    /**
     * 设置角色信息
     */
    public function set()
    {

        $id        = $this->request->param('id', 0, 'int');
        $roleModel = new RoleModel();
        if ($this->request->isPost()) {
            $name   = $this->request->param('name');
            $status = $this->request->param('status');
            //验证数据
            $validate = new RoleValidate();
            if (!$validate->check(['name' => $name, 'status' => $status])) {
                $this->error($validate->getError());
            }
            $currentTime = time();
            if (!$id) {
                //新增
                $count = $roleModel->where('name', '=', $name)->count();
                if ($count) {
                    $this->error('该角色名称已存在，请输入其他的角色名称~~');
                }
                $roleModel->created_time = $currentTime;
            } else {
                //编辑
                $count = $roleModel->where('name', '=', $name)->whereNotIn('id', $id)->count();
                if ($count) {
                    $this->error('该角色名称已存在，请输入其他的角色名称~~');
                }
                $roleModel = $roleModel->find($id);
            }
            $roleModel->updated_time = $currentTime;
            $roleModel->name         = $name;
            $roleModel->status       = $status;

            $result = $roleModel->save();
            if ($result) {
                $this->success('操作成功~~', url('admin/role/index'));
            } else {
                $this->error('操作失败~~');
            }
        }
        $role = null;
        if ($id) {
            $role = $roleModel->find($id);
        }

        $this->assign('role', $role);

        $status = BoolStatus::getLables();
        $this->assign('status', $status);
        return $this->fetch('role/set');
    }

    /**
     * 设置角色和权限的关系逻辑
     */
    public function access()
    {
        $roleId = $this->request->param('role_id');

        if ($this->request->isPost()) {
            $param     = $this->request->param();
            $accessIds = isset($param['access_ids']) ? $param['access_ids'] : [];

            if (!$roleId) {
                $this->error('您指定的角色不存在');
            }

            $role = RoleModel::field(['id'])->find($roleId);

            if (!$role) {
                $this->error('您指定的角色不存在');
            }

            //开启事务
            Db::startTrans();
            try {

                //取出所有已分配的权限
                $roleAccessIds = RoleAccess::where('role_id', '=', $roleId)->column('access_id');

                //要新增的权限
                $newAccess = array_diff($accessIds, $roleAccessIds);
                if ($newAccess) {
                    foreach ($newAccess as $accessId) {
                        $roleAccessModel               = new RoleAccess();
                        $roleAccessModel->role_id      = $roleId;
                        $roleAccessModel->access_id    = $accessId;
                        $roleAccessModel->created_time = time();
                        $roleAccessModel->save();
                    }
                }

                //要删除的权限
                $deleteAccess = array_diff($roleAccessIds, $accessIds);
                if ($deleteAccess) {
                    foreach ($deleteAccess as $accessId) {
                        RoleAccess::destroy(['role_id' => $roleId, 'access_id' => $accessId]);
                    }
                }

                // 提交事务
                Db::commit();

            } catch (\Exception $e) {
                // 回滚事务
                Db::rollback();
                $this->error('操作失败~~');
            }
            $this->success('操作成功~~', url('admin/role/index'));
        }

        //当前角色名称
        $role = RoleModel::field(['id', 'name'])->find($roleId);
        $this->assign('role', $role);

        //获取所有权限
        $accessList = AccessModel::where('status', '=', BoolStatus::OPEN)
            ->order('id', SORT_DESC)
            ->field(['id', 'title'])
            ->select();
        $this->assign('accessList', $accessList);

        //取出所有已分配的权限
        $roleAccessIds = RoleAccess::where('role_id', '=', $roleId)->column('access_id');
        $this->assign('roleAccessIds', $roleAccessIds);
        return $this->fetch('role/access');
    }
}